using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

using Caliburn.Micro;

using Haushaltsbuch.Domain.Authentication;
using Haushaltsbuch.Events;
using Haushaltsbuch.Helpers;
using Haushaltsbuch.ViewModels.Interfaces;

namespace Haushaltsbuch.ViewModels
{
    [Export(typeof(ILoginViewModel))]
    public class LoginViewModel :Screen, IShellContent, ILoginViewModel
    {
        private readonly IEventAggregator events;
        private int attemps;
        private string username;
        private string password;

        public string Username
        {
            get { return this.username; }
            set
            {
                if (value == this.username) return;
                this.username = value;
                this.NotifyOfPropertyChange(() => this.Username);
            }
        }

        public string Password
        {
            get { return this.password; }
            set
            {
                if (value == this.password) return;
                this.password = value;
                this.NotifyOfPropertyChange(() => this.Password);
            }
        }

        private int Attemps
        {
            get { return this.attemps; }
            set
            {
                this.attemps = value;
                this.NotifyOfPropertyChange(() => this.CanLogin);
            }
        }

        public bool CanLogin
        {
            get { return this.Attemps < 3; }
        }

        public LoginViewModel(IEventAggregator events)
        {
            this.Username = "Admin";
            this.Password = "test1";

            this.Attemps = 0;
            this.events = events;
        }

        //public Shop[] GetShops()
        //{
        //    using (var ctx = new HaushaltsbuchContext())
        //    {
        //        var shops = ctx.Shops.ToArray();

        //        return shops;
        //    }
        //}

        public void Login()
        {
            HaushaltsbuchPrincipal.Login(Username,Password);
            this.events.Publish(new CurrentUserChangedEvent());
            if (!Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                this.events.Publish(new MessageToUserEvent(string.Format("Versuch {0}/3", ++this.Attemps), MessageType.Error));
                return;
            }
            
            this.events.Publish(new ViewChangeEvent("blank"));
            


        }
    }
}